package MultiNetworkingBase;

//This includes everything in the server side game logic

import java.io.IOException;
import java.util.ArrayList;

import javax.management.timer.Timer;

import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Server;

import MultiNetworkingBase.Network.WarTugConnection;
import MultiNetworkingBase.Network.RegisterName;

public class WarTugServer implements Runnable {
	Server server; //Server listening for client connections
	public boolean end = false;
	public int numPlayers;
	public long start = 0;
	private ArrayList<SimpleUnit> allTempUnits = new ArrayList<SimpleUnit>(); //TODO: This will later be removed, this is used to test the server
	private ArrayList<SimpleUnit> allUnits = new ArrayList<SimpleUnit>(); //Holds all units tracked server side

    public WarTugServer () throws IOException {
    	//Set-up Server here
    	server = new Server() {
            protected Connection newConnection () {
                    // By providing our own connection implementation, we can store per
                    // connection state without a connection ID to state look up.
                    return new WarTugConnection();
            }
    	};
    	
    	// For consistency, the classes to be sent over the network are
        // registered by the same method for both the client and server.
        Network.register(server);
        
        server.addListener(new Listener() {
            public void received (Connection c, Object object) {
                // We know all connections for this server are actually ChatConnections.
            	WarTugConnection connection = (WarTugConnection)c;

                if (object instanceof RegisterName) {
                	if (numPlayers==2) return; //Only let two players on server
                    if (connection.name != null) return; // Ignore the object if the name is invalid.
                    String name = ((RegisterName)object).name;
                    if (name == null) return; //Ignore if no name
                    name = name.trim();
                    if (name.length() == 0) return;
                    // Store the name on the connection.
                    connection.name = name;
                    connection.playerNum = numPlayers; //Give player a player number based upon order of connection
                    
                    //TODO: testing code for server, remove later
                    synchronized(allTempUnits){
	                    for (int i = 0; i<40; i++){
	                    	allTempUnits.add(new SimpleUnit(UnitType.treeOfLife, 12 +20*i, 12+20*i));
	                    	allTempUnits.add(new SimpleUnit(UnitType.treeOfLife, 12 +20*i+10, 12+20*i));
	                    	allTempUnits.add(new SimpleUnit(UnitType.treeOfLife, 12 +20*i+20, 12+20*i));
	                    }
	                    for (SimpleUnit unit : allTempUnits){
	                    	unit.xSpeed = .15;
	                    }
                    }
                    
                    //increment number of players
                    numPlayers++;
                    return;
                }
                if (object instanceof SimpleUnit) {
                	//Don't know if this will ever happen...
                    return;
                }
            }
            public void disconnected (Connection c) {
            	//Need to decide what to do if a client dcs
            }
        });

        server.bind(Network.port); //Binds all of the server listeners to a port
        server.start();
    }
    
    public void run() {
    	//Here is where we have the main server game loop
		start = System.currentTimeMillis();
    	while (!end){
    		long delta = System.currentTimeMillis() - start;
    		start = System.currentTimeMillis();
    		try {
				Thread.sleep(100); //TODO:Perhaps make new function to mimic the effects of Display.sync(100), it might have to use time stamps, though...
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		
    		//TODO: this is only server testing, to be removed later
    		synchronized(allTempUnits) {
	    		for (SimpleUnit unit : allTempUnits){
	    			allUnits.add(unit);
	    		}
	    		allTempUnits = new ArrayList<SimpleUnit>();
    		}
    		
    		//Send units to the clients, TODO:Maybe have this in unit manager.  
    		//Pro: looping through units is done in unit manager, cleaner code.  
    		//Con: Must pass server to unit manager
    		for (SimpleUnit unit : allUnits){
    			unit.move(delta);
    			server.sendToAllTCP(unit);
    		}
    	}
    }
}
